package com.geek.core.config.security;

import com.geek.tool.HttpWebUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @功能 系统用户登录结果处理器
 * @作者 MaxBill
 * @时间 2018年8月1日
 * @邮箱 maxbill1993@163.com
 */
@Component
public class SysUserDetailsHandler implements AuthenticationSuccessHandler, AuthenticationFailureHandler, LogoutSuccessHandler {

    /**
     * 认证成功
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        HttpWebUtil.setRequestAttribute("flag", "s");
        HttpWebUtil.setRequestAttribute("msgs", "登录成功...");
        HttpWebUtil.setSessionAttribute("sysUser", authentication.getPrincipal());
        HttpWebUtil.getRequest().getRequestDispatcher("/sys/user/deal").forward(request, response);
    }

    /**
     * 认证失败
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException authenticationException) throws IOException, ServletException {
        String errorMsgs = "";
        //UsernameNotFoundException 用户找不到
        //BadCredentialsException 坏的凭据
        //AccountExpiredException 账户过期
        //LockedException 账户锁定
        //DisabledException 账户不可用
        //CredentialsExpiredException 证书过期
        System.out.println(authenticationException.getMessage());
        switch (authenticationException.getMessage()) {
            case "Not Found User":
                errorMsgs = "用户不存在...";
                break;
            case "Bad credentials":
                errorMsgs = "密码错误...";
                break;
            case "Not Found UserRole":
                errorMsgs = "用户权限低...";
                break;
            default:
                errorMsgs = "登录失败...";
                break;
        }
        HttpWebUtil.setRequestAttribute("flag", "f");
        HttpWebUtil.setRequestAttribute("msgs", errorMsgs);
        HttpWebUtil.getRequest().getRequestDispatcher("/sys/user/deal").forward(request, response);
    }

    /**
     * 登出成功
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
    }

}
